package org.obm.mina;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;

public final class MinaUtil {

	public static final byte CR = '\r';
	public static final byte LF = '\n';
	public static final byte DOT = '.';

	public static final int INITIAL_CAPACITY = 32;

	/**
	 * Ensure that specified buffer has at least enough capacity to accomodate
	 * 'minSize' additional bytes, but not more than 'maxSize' additional bytes.
	 * If 'maxSize' is 0, then there is no limit.
	 * 
	 * @param bb
	 *            the ByteBuffer to expand, or null to create a new one
	 * @param minSize
	 *            minimum additional capacity for resulting byte buffer
	 * @param maxSize
	 *            maximum additional capacity, or -1 for no maximum
	 * @return the resulting, possible expanded, ByteBuffer
	 */
	public static ByteBuffer expand(ByteBuffer bb, int minSize, int maxSize) {
		if (maxSize != -1 && maxSize < minSize) {
			throw new IllegalArgumentException("maxSize < minSize");
		}
		if (bb == null) {
			int size = Math.max(minSize, INITIAL_CAPACITY);
			if (maxSize != -1 && size > maxSize)
				size = maxSize;
			return ByteBuffer.allocate(size);
		}
		if (bb.remaining() >= minSize)
			return bb;
		int capacity = Math.max((bb.capacity() * 3) / 2 + 1, bb.position()
				+ minSize);
		if (maxSize != -1) {
			capacity = Math.max(capacity, bb.position() + maxSize);
		}
		ByteBuffer tmp = ByteBuffer.allocate(capacity);
		bb.flip();
		return tmp.put(bb);
	}

	public static ByteBuffer expand(ByteBuffer bb, int minSize) {
		return expand(bb, minSize, -1);
	}

	public static IoBuffer toMinaByteBuffer(ByteBuffer bb) {
		return IoBuffer.wrap(bb);
	}
}
